var ADMIN = (function (parent, $) {
    var common = parent.common = parent.common || {};
    common.isReplaceUrl = common.isReplaceUrl || false;

    function eventHandler() {
        /**
         *  关键词查询的事件绑定
         */
        $(document).off('focus', '[name="AreaName"]');
        $(document).on('focus', '[name="AreaName"]', showSugList);

        // $(document).off('blur', '[name="AreaName"]');
        // $(document).on('blur', '[name="AreaName"]', hideSugList);

        $(document).off('change', '[name="AreaName"]');
        $(document).on('change', '[name="AreaName"]', updateSugList);

        $(document).off('click', '.sug-store');
        $(document).on('click', '.sug-store', selectSugStore);

        $(document).off('click', '.sug-store-del');
        $(document).on('click', '.sug-store-del', removeSuglist);

        // 返回按钮的事件绑定
        $(document).off('click', '.history-back');
        $(document).on('click', '.history-back', function () {
            history.back();
        });

        //禁用页面A标签右键菜单
        $(document).off('contextmenu', 'a');
        $(document).on('contextmenu', 'a', function (e) {
            return false;
        });

        //列表页字段隐藏后用layer.tips显示。
        $(document).on('mouseover', '.text-overflow-tips', function(e){
            e.stopPropagation();
            var tableTdText = $(this).text();
            var operationBtn = $(this).find('div.btn-group');
            if (tableTdText.length != 0 && operationBtn.length === 0) {
                layer.tips('' + tableTdText + '', $(this), {
                    tips: [3, '#00B5FF'],
                    more: false
                });
            }
        });

        // 防止按Enter键自动提交表单
        $(document).off('keydown', 'form');
        $(document).on('keydown', 'form', preventFormAutoSubmit);

        // 共通跳转到系统内部的事件绑定
        $(document).off('click', 'a.location-href');
        $(document).on('click', 'a.location-href', locationHref);

        // 展开版本发布信息内容
        $(document).off('click', '.notify-content');
        $(document).on('click', '.notify-content', showReleaseVersionInfo);

        // 收起版本发布信息内容
        $(document).off('click', 'release-version-info button.close');
        $(document).on('click', '.release-version-info button.close', hideReleaseVersionInfo);
    }

    /*
     保存当前已激活的标签页Id
     */
    function saveActiveTab() {
        var $activeTab =  $('.wrapper-right .tab-pane.active');
        if ( $activeTab.length > 0) {
            $('.wrapper-right').data('active-tab',"#" + $activeTab.attr('id'));
        }
    }

    /**
     * 异步加载页面主要内容
     * @param $target  事件目标元素如：菜单选项或按钮
     * @param url  请求地址
     * @param container  所请求页面的容器
     * @param callback  页面加载成功的回调函数
     */
    function loadContentMain($target, url, container, callback) {
        url = url || $target.attr('href');
        if (!url || url === '' || url === '#') {
            return;
        }

        if ($target) {
            $target.addClass("disabled");

            var menuId = $target.attr('menu-id');
            if (menuId) {
                if (url.indexOf('?') === -1) {
                    url = url + '?menuId=' + menuId;
                } else {
                    url = url + '&menuId=' + menuId;
                }
            }
        }

        url = url.replace('/sitemesh/', '/nositemesh/');
        container = container || '.wrapper';

        saveActiveTab();

        $(container).loadHtml({
            url: url,
            success: function() {
                //记录旧页面页面状态
                if ($target) {
                    parent.historyBack.recordCurrtentState(container, $target.hasClass('not-record'));
                    parent.historyBack.updateCurrtentUrl(url);
                }
                //激活当前容器所在的标签
                $('li[href="'+ container +'"][role="tab"] ').tab('show');
            },
            loadSuccess: function() {
                // 创建面包屑路径
                parent.breadcrumb.createNavLocation();
                //记录新页面页面状态
                parent.menu.saveMenuStorage();
                parent.historyBack.recordCurrtentState(container);
                parent.historyBack.isPopState = false;

                //清除已启动二次组态获取实时数据的函数调用
                if (parent.secondConfig &&
                    parent.secondConfig.inter &&
                    parent.secondConfig.inter >= 0) {
                    clearInterval(parent.secondConfig.inter);
                }

                //清除已启动设备运行实时数据的函数调用
                if (parent.deviceCharts &&
                    parent.deviceCharts.inter &&
                    parent.deviceCharts.inter >= 0) {
                    clearInterval(parent.deviceCharts.inter);
                }

                if (callback) {
                    callback();
                }
            },
            complete: function() {
                $('.modal').modal('hide');
                $('.modal-backdrop').remove();
                $('body').removeClass('modal-open');
                if ($target) {
                    $target.removeClass("disabled");
                }
            }
        });
    }

    /**
     * 跳转系统内部页面的事件处理
     * @param e
     */
    function locationHref(e) {
        e.preventDefault();
        var url = $(this).attr('href');
        if (url === '#' || url === '') {
            return;
        }

        if(parent.menu && parent.menu.clearMenuStorage) {
            parent.menu.clearMenuStorage();
        }

        localStorage.setItem("isReplaceUrl", true);
        location.href = url;
    }
    
    function showReleaseVersionInfo() {
        var $releaseVersionInfo = $('.release-version-info');
        if ($releaseVersionInfo.find('.version-info').length > 0) {
            $releaseVersionInfo.removeClass('fadeOutRight');
            $releaseVersionInfo.addClass('fadeInRight');
            $releaseVersionInfo.show();
        }
    }
    
    function hideReleaseVersionInfo() {
        var $releaseVersionInfo = $('.release-version-info');
        $releaseVersionInfo.removeClass('fadeInRight');
        $releaseVersionInfo.addClass('fadeOutRight');
        setTimeout(function () {
            $releaseVersionInfo.hide();
        }, 750);
    }

    /**
     *
     * @param arr    需要加载的script文件路径数组
     * @param iterator 获取并添加script文件
     * @param callback
     * @returns {*}
     */
    var isLoadingScripts = false;
    function eachSeries(arr, iterator, callback) {
        if (isLoadingScripts) {
            setTimeout(function () {
                eachSeries(arr, iterator, callback);
            }, 100);
            return false;
        } else {
            isLoadingScripts = true;
        }

        callback = callback || function () {};
        if (!arr.length || isScriptsExist(arr)) {
            isLoadingScripts = false;
            return callback();
        }

        var completed = 0;
        var iterate = function () {
            iterator(arr[completed], function (err) {
                if (err) {
                    isLoadingScripts = false;
                    callback(err);
                    callback = function () {};
                } else {
                    completed += 1;
                    if (completed >= arr.length) {
                        isLoadingScripts = false;
                        callback(null);
                    } else {
                        iterate();
                    }
                }
            });
        };
        iterate();
    }

    /**
     *
     * @param url  script文件路径
     * @param callback
     * @returns {undefined}
     */
    function getScript(url, callback) {
        if (typeof url === 'undefined') {
            callback();
            return false;
        }

        var head = document.getElementsByTagName('head')[0];
        var script = document.createElement('script');
        script.src = url;

        var done = false;
        // Attach handlers for all browsers
        script.onload = script.onreadystatechange = function() {
            if (!done && (!this.readyState ||
                this.readyState == 'loaded' || this.readyState == 'complete')) {
                done = true;
                if (callback)
                    callback();

                // Handle memory leak in IE
                script.onload = script.onreadystatechange = null;
            }
        };

        head.appendChild(script);

        // We handle everything using the script element injection
        return undefined;
    }

    /**
     * 检查页面是否已经加载指定插件
     * @param scripts
     * @returns {boolean}
     */
    function isScriptsExist(scripts) {
        var scriptsLength = scripts.length;
        var indexArr = [];
        scripts.forEach(function (url, i) {
            var pluginArr = url.split('/');
            var pluginName = pluginArr[pluginArr.length - 1];
            $('script').each(function (j, script) {
                var src = $(script).attr('src');
                if (src &&　src.match(pluginName)) {
                    indexArr.push(i);
                }
            });
        });

        indexArr.forEach(function (num) {
            delete scripts[num];
        });

        return indexArr.length === scriptsLength;
    }

    function moveTableTitle(_table) {
        var tableToolbar = _table.parents('.fixed-table-container').siblings('.fixed-table-toolbar').children();
        var $ifSearch = _table.parents('.table-box-content').siblings('.table-box-title').find('.fuzzy-search');
        var searchBtn = '<a class="input-group-btn">';

        searchBtn += '<button type="button" class="btn btn-blue fuzzy-search">';
        searchBtn += '<i class="sys-icons search-icon"></i>';
        searchBtn += '</button></a>';

        if (!$ifSearch[0]) {
            tableToolbar.append($(searchBtn));
            tableToolbar.addClass('input-group');
            tableToolbar.children('[placeholder="搜索"]').attr('placeholder', '按Enter键可模糊查询');
            _table.parents('.table-box-content').siblings('.table-box-title').append(tableToolbar);
        }
    }

    function initDatetimepicker() {

        $('.form_datetime').each(function (index, dateItem) {
            var afterNowDate = '', beforeNowDate = '';
            var minView = $(dateItem).attr('min-view');
            if (minView) {
                minView = parseInt(minView);
            } else {
                minView = 0;
            }

            var format = 'yyyy-mm-dd';
            switch (minView) {
                case 0:
                    format = 'yyyy-mm-dd hh:ii';
                    break;
                case 1:
                    format = 'yyyy-mm-dd hh:00';
                    break;
                case 2:
                    format = 'yyyy-mm-dd';
                    break;
            }

            if($(dateItem).is('.afterNowDate')){
                afterNowDate = new Date();
            }
            if($(dateItem).is('.beforeNowDate')){
                beforeNowDate = new Date();
            }

            $(dateItem).datetimepicker({
                format: format,
                language: 'zh-CN',
                minView: minView,
                autoclose: true,
                startDate: afterNowDate || '',
                endDate: beforeNowDate || '',
                todayBtn: true
            }).on('changeDate', function () {
                var dateName = $(this).attr('date-name');
                if ($(this).is('.startDate[date-name="' + dateName + '"]')) {
                    if ($('.endDate[date-name="' + dateName + '"]').val() !== "") {
                        $(this).datetimepicker('setEndDate', $('.endDate[date-name="' + dateName + '"]').val());
                    }
                    $('.endDate[date-name="' + dateName + '"]').datetimepicker('setStartDate', $('.startDate[date-name="' + dateName + '"]').val());
                }

                if ($(this).is('.endDate[date-name="' + dateName + '"]')) {
                    if ($('.startDate[date-name="' + dateName + '"]').val() !== "") {
                        $(this).datetimepicker('setStartDate', $('.startDate[date-name="' + dateName + '"]').val());
                    }
                    $('.startDate[date-name="' + dateName + '"]').datetimepicker('setEndDate', $('.endDate[date-name="' + dateName + '"]').val());
                }
            });
        })
    }

    /**
     * 向下渐变推进
     * @param $el
     */
    function fadeInDown($el) {
        $el.addClass('fadeInDown');
        setTimeout(function () {
            $el.removeClass('fadeInDown');
        }, 1000);
    }

    /**
     * 向上渐变退出
     * @param $el
     */
    function fadeOutUp($el) {
        $el.addClass('fadeOutUp');
        setTimeout(function () {
            $el.removeClass('fadeOutUp');
            $el.remove();
        }, 1000);
    }

    /**
     * 表单验证的警告消息栏
     * @param msg
     * @returns {string}
     */
    function alertMsg(msg) {
        var msgHtml = '<div class="alert alert-warning alert-dismissible" role="alert">' +
            '<button type="button" class="close" data-dismiss="alert" aria-label="Close">' +
            '<span aria-hidden="true">&times;</span>' +
            '</button>'+
            '<i class="sys-icons warning-icon"></i>'+
            '<span class="msg">'+ msg +'</span>' +
        '</div>';
        return msgHtml;
    }

    /**
     * 系统错误等警示栏
     * @param msg
     * @returns {string}
     */
    function alertError(msg) {
        var $alertError = $('<div class="alert alert-error alert-dismissible animated" role="alert">' +
            '<button type="button" class="close" data-dismiss="alert" aria-label="Close">' +
            '<i class="sys-icons close-icon"></i>' +
            '</button>'+
            '<i class="sys-icons danger-icon"></i>'+
            '<span class="msg">'+ msg +'</span>' +
        '</div>');

        var $contentMain =  $('.content-main');
        if ($contentMain.children('.alert').length !== 0) {
            $contentMain.children('.alert').remove();
        }
        $contentMain.prepend($alertError);
        fadeInDown($alertError);

        setTimeout(function () {
            fadeOutUp($alertError);
        }, 3000);
    }

    /**
     * 提示类，软件版本升级成功等信息栏
     * @param msg
     * @returns {string}
     */
    function alertInfo(msg) {
        var $alertInfo = $('<div class="alert alert-info alert-dismissible animated" role="alert">' +
            '<button type="button" class="close" data-dismiss="alert" aria-label="Close">' +
            '<i class="sys-icons close-icon"></i>' +
            '</button>'+
            '<i class="sys-icons info-icon"></i>'+
            '<span class="msg">'+ msg +'</span>' +
        '</div>');

        var $contentMain =  $('.content-main');
        if ($contentMain.children('.alert').length !== 0) {
            $contentMain.children('.alert').remove();
        }
        $contentMain.prepend($alertInfo);
        fadeInDown($alertInfo);

        setTimeout(function () {
            fadeOutUp($alertInfo);
        }, 3000);
    }

    /**
     * 提示浏览器版本等信息
     * @param msg
     * @returns {string}
     */
    function alertBrowserInfo(msg) {
        var $alertInfo = $('<div class="alert alert-browser-info alert-dismissible animated" role="alert">' +
            '<button type="button" class="close" data-dismiss="alert" aria-label="Close">' +
            '<i class="sys-icons close-icon"></i>' +
            '</button>'+
            '<i class="sys-icons info-icon"></i>'+
            '<span class="msg">'+ msg +'</span>' +
            '</div>');

        var $body =  $('body');
        if ($body.children('.alert').length !== 0) {
            $body.children('.alert').remove();
        }
        $body.prepend($alertInfo);
        fadeInDown($alertInfo);
    }

    /**
     * 确认摸态框
     * @param title 摸态框标题
     * @param bodyUrl 请求摸态框body的地址
     * @param confirmCallBack 确认按钮的回调函数
     * @param cancelCallBack 取消按钮的回调函数
     */
    function alertConfirm(title, bodyUrl, confirmCallBack, cancelCallBack) {
        if ($('.alert-confirm').length !== 0) {
            $('.alert-confirm').modal('show');
            return;
        }

        if (!title || !bodyUrl|| !confirmCallBack) {
            return
        }

        var $alertConfirm = $('<div class="modal fade alert-onfirm" tabindex="-1" role="dialog">' +
            '<div class="modal-dialog" role="document">' +
            '<div class="modal-content">' +
            '<div class="modal-header">' +
            '<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>' +
            '<h4 class="modal-title">'+ title +'</h4>' +
            '</div>' +
            '<div class="modal-body">' +
            '</div>' +
            '<div class="modal-footer">' +
            '<a type="button" class="btn btn-blue confirm-btn">' +
            '<i class="sys-icons save-icon"></i>确定' +
            '</a>' +
            '<a type="button" class="btn btn-gray cancel-btn" data-dismiss="modal">' +
            '<i class="sys-icons cancel-icon"></i>取消' +
            '</a>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div>');

        $alertConfirm.find('.confirm-btn').on('click', confirmCallBack);
        $alertConfirm.find('.cancel-btn').on('click', cancelCallBack);

        $.ajax({
            type: 'GET',
            dataType: "html",
            url: bodyUrl,
            cache: false
        }).done(function (resultData, textStatus, jqXHR) {
            $alertConfirm.find('.modal-body').append(resultData);
            $('body').append($alertConfirm);
            $alertConfirm.modal('show');
            console.log('加载成功');

        }).fail(function (jqXHR, textStatus, errorThrown) {
            alertError('确认摸态框内容请求失败！');
            console.log('请求失败');
        });
    }


    /*
     判断浏览器版本
     不传参数返回当前IE版本号；
     如果不是IE内核浏览器，返回false。
     */
    function IETester(userAgent) {
        var UA = userAgent || navigator.userAgent;
        if (/msie/i.test(UA)) {
            return UA.match(/msie (\d+\.\d+)/i)[1];
        } else if (~UA.toLowerCase().indexOf('trident') && ~UA.indexOf('rv')) {
            return UA.match(/rv:(\d+\.\d+)/)[1];
        }
        return false;
    }

    /**
     * 检查当前浏览器是否兼容，并给予提示
     */
    function testBrowser() {
        if (typeof browser === 'undefined') {
            return;
        }

        if (browser.quirks) {
            return;
        }

        if (browser.name !== 'chrome') {
            if (browser.name === 'ie') {
                if (browser.documentMode < 9) {
                    return;
                }
                if (browser.version < 9) {
                    alertBrowserInfo('您正在使用IE内核并且内核版本低于IE9的浏览器访问本系统，' +
                        '为了保证更好的用户体验，建议您使用先进的谷歌浏览器或将您的360浏览器切换到极速模式！');
                }
            } else {
                alertBrowserInfo('您正在使用不是谷歌或IE内核的浏览器访问本系统，' +
                    '为了保证更好的用户体验，建议您使用先进的谷歌浏览器或360浏览器的极速模式！');
            }
        }
    }

    /**
     * 关键词查询
     * */
    function showSugList() {
        $(this).next().show();
    }

    function hideSugList() {
        $('.sug').hide();
    }

    function updateSugList() {
        var keyWord = $(this).val().trim();
        $('.sug-store').each(function (i, item) {
            var dataKey = $(item).attr('data-key');
            if (dataKey.match(keyWord)) {
                $(item).show();
            } else {
                $(item).hide();
            }
        });
    }

    function selectSugStore() {
        var dataKey = $(this).attr('data-key');
        console.log(dataKey);
        $('[name="AreaName"]').val(dataKey);
        hideSugList();
    }

    function removeSuglist(e) {
        e.stopPropagation();
        $(this).parent('li').remove();
    }

    //列表页的字段隐藏
    function textOverflowTips(value){
        if(!value){
            return;
        }
        var tdTextBox = '<div class="text-overflow-tips text-overflow">';
        tdTextBox += '' + value + '';
        tdTextBox += '</div>';
        return tdTextBox;
    }

    /**
     * 清除表单数据
     * @param $form
     */
    function clearForm($form) {
        $form.find('input:text, input:password, input:hidden, input:file, textarea').val('');
        $form.find('input:radio, input:checkbox')
            .removeAttr('checked').removeAttr('selected');
        $form.find('select').children(':first').attr('selected', true);
    }

    /**
     * 填充表单数据
     * @param $form
     * @param formData
     */
    function fillFormData($form,formData){
        var key,value,tagName,type,arr;
        for(var attr in formData){
            key = attr;
            value = formData[attr];

            $form.find('[name='+ key +']').each(function(){
                tagName = $(this)[0].tagName;
                type = $(this).attr('type');
                if(tagName=='INPUT'){
                    if(type=='radio'){
                        $(this).attr('checked',$(this).val()==value);
                    }else if(type=='checkbox'){
                        arr = value.split(',');
                        for(var i =0;i<arr.length;i++){
                            if($(this).val()==arr[i]){
                                $(this).attr('checked',true);
                                break;
                            }
                        }
                    }else{
                        $(this).val(value);
                    }
                }else if(tagName=='SELECT' || tagName=='TEXTAREA'){
                    $(this).val(value);
                }
            });
        }
    }

    function preventFormAutoSubmit(e) {
        if ($(e.target).is('textarea')) {
            return
        }

        if (e.keyCode == 13) {
            return false;
        }
    }

    /**
     * 任务箭头的js动态实现
     * arr
     *
     */
    function taskArrow(arr){
        arr.forEach(function(item, i){
            var $taskHtml = $('<div class="task-box">' +
                '<div class="task-left"></div> ' +
                '<div class="task-text" title="'+arr[i].txt+'">'+
                '<div class="txt">'+arr[i].txt+'</div>'+
                '</div>'+
                '<div class="task-right"></div>' +
                '</div>');
            if (item.status === 1) {
                $taskHtml.children().addClass('complete');
            }
            $(".task-arrow").append($taskHtml);
        })
        $(".task-box").css({
            'width':'calc('+1/$(".task-box").length*100+'% + 18px)'
        });
        $(".task-box").last().css({
            'width':'calc('+1/$(".task-box").length*100+'%)'
        });
    }


    /**
     * 任务箭头的js动态实现
     * arr
     *
     */
    function circleTask(arr){
        arr.forEach(function(item,i){
            var $circleHtml = $('<div class="circle-group">'+
                '<div class="circle"></div>'+
                '<div class="txt" title="'+arr[i].txt+'">'+arr[i].txt+'</div>'+
                '<div class="line"></div>'+
                '</div>');
            if(item.status === 1){
                $circleHtml.children().addClass('complete');
            }
            $(".circle-taskbar").append($circleHtml);
        })
    }

    /**
     * 自动添加标签的js动态实现
     *
     *
     */
    function autoAddTags(num){
        var tagsTextWidth = (1/parseInt(num))*100;
        var  offsetWidth = 15;
        $(".tags-text").keydown(function(event){
            var arr=$(".tags-txt span");
            if(event.keyCode == '32'&& arr.length<parseInt(num)){
                var tagsText=$("#tags-text").val();
                if(tagsText.replace(/(^\s*)|(\s*$)/g,"")!==""){
                    tagsTxt=$(".tags-txt").html() + "<div>"+"<span title="+tagsText+" class='label-txt'>"+tagsText+"</span>"+"<b>×</b>"+"</div>";
                    $(".tags-txt").html(tagsTxt);
                    $('#tags-text').val("");
                    $(".tags-txt div").css("width",'calc('+tagsTextWidth+'% - '+ offsetWidth +'px)');
                }
            }
            else if(arr.length>=parseInt(num)){
                $("#tags-text").attr("disabled",'false');
            }
            return arr;
        });
        $(".tags-txt").on('click','b',function(){
            $(this).parent().remove();
            var arrNum=$(".tags-txt span").length;
            if(arrNum<parseInt(num)){
                $("#tags-text").removeAttr("disabled");
            }
        })
    }

    //邮箱自动补全
    function mailAutoComplete($target, options) {
        var defaults = {
            className: "emailist",
            email:  ["petrochina.com.cn"], //邮件数组
            zIndex: 11
        };
        // 最终参数
        var params = $.extend({}, defaults, options || {});

        // 是否现代浏览器
        var isModern = typeof window.screenX === "number", visibility = "visibility";
        // 键值与关键字
        var key = {
            "up": 38,
            "down": 40,
            "enter": 13,
            "esc": 27,
            "tab": 9
        };
        // 组装HTML的方法
        var fnEmailList = function(input) {
            var htmlEmailList = '', arrValue = input.value.split("@"), arrEmailNew = [];
            $.each(params.email, function(index, email) {
                if (arrValue.length !== 2 || arrValue[1] === "" || email.indexOf(arrValue[1].toLowerCase()) === 0) {
                    arrEmailNew.push(email);
                }
            });
            $.each(arrEmailNew, function(index, email) {
                htmlEmailList = htmlEmailList + '<li'+ (input.indexSelected===index? ' class="on"':'') +'>'+ arrValue[0] + "@" + email +'</li>';
            });
            return htmlEmailList;
        };
        // 显示还是隐藏
        var fnEmailVisible = function(ul, isIndexChange) {
            var value = $.trim(this.value), htmlList = '';
            if (value === "" || (htmlList = fnEmailList(this)) === "") {
                ul.css(visibility, "hidden");
            } else {
                isIndexChange && (this.indexSelected = -1);
                ul.css(visibility, "visible").html(htmlList);
            }
        };

        return $target.each(function() {
            this.indexSelected = -1;
            // 列表容器创建
            var element = this;
            var eleUl = $('<ul></ul>').css({
                position: "absolute",
                marginTop: element.offsetHeight,
                minWidth: element.offsetWidth - 2,
                visibility: "hidden",
                zIndex: params.zIndex
            }).addClass(params.className).bind("click", function(e) {
                var target = e && e.target;
                if (target && target.tagName.toLowerCase() === "li") {
                    $(element).val(target.innerHTML).trigger("input");
                    $(this).css(visibility, "hidden");
                    element.focus(); // add on 2013-11-20
                }
            });
            $(this).before(eleUl);
            // IE6的宽度
            if (!window.XMLHttpRequest) {
                eleUl.width(element.offsetWidth - 2);
            }

            // 不同浏览器的不同事件
            isModern? $(this).bind("input", function() {
                fnEmailVisible.call(this, eleUl, true);
            }): element.attachEvent("onpropertychange", function(e) {
                if (e.propertyName !== "value") return;
                fnEmailVisible.call(element, eleUl, true);
            });

            $(document).on({
                "click": function(e) {
                    var target = e && e.target, htmlList = '';
                    if (target == element && element.value && (htmlList = fnEmailList(element, params.email))) {
                        eleUl.css(visibility, "visible").html(htmlList);
                    } else if (target != eleUl.get(0) && target.parentNode != eleUl.get(0)) {
                        eleUl.css(visibility, "hidden");
                    }
                },
                "keydown": function(e) {
                    var eleLi = eleUl.find("li");
                    if (eleUl.css(visibility) === "visible") {
                        switch (e.keyCode) {
                            case key.up: {
                                element.indexSelected--;
                                if (element.indexSelected < 0) {
                                    element.indexSelected = -1 + eleLi.length;
                                }
                                e.preventDefault && e.preventDefault();
                                break;
                            }
                            case key.down: {
                                element.indexSelected++;
                                if (element.indexSelected >= eleLi.length) {
                                    element.indexSelected = 0;
                                }
                                e.preventDefault && e.preventDefault();
                                break;
                            }
                            case key.enter: {
                                e.preventDefault();
                                eleLi.get(element.indexSelected) && $(element).val(eleLi.eq(element.indexSelected).html());
                                eleUl.css("visibility", "hidden");
                                break;
                            }
                            case key.tab: case key.esc: {
                            eleUl.css("visibility", "hidden");
                            break;
                        }
                        }
                        if (element.indexSelected !== -1) {
                            eleUl.html(fnEmailList(element));
                        }
                    }
                }
            });
        });
    }

    /**
     * 根据length转换字符或浮动数值为小数点后指定位数的字符串数值
     * @param num
     * @param length
     * @returns {*}
     */
    function numToFloat(num, length) {
        if (isNaN(num)) {
            return num;
        }

        var floatNum = parseFloat(num);
        if (floatNum % 1 === 0) {
            return num;
        } else {
            return floatNum.toFixed(length);
        }
    }
    
    function processPrompt($target, state) {
        var processPromptHtml = '';
        if(!$target[0]){
            return;
        }
        switch (state) {
            case 0 :
                processPromptHtml = '<div class="current-process">' +
                    '<i class="sys-icons current-process-icon"></i>当前状态：' +
                    '<span>待调度室领导处理</span>' +
                    '</div>';
                break;
            case 1 :
                processPromptHtml = '<div class="stay-deal-with-process">' +
                    '<div class="dashed-line">' +
                    '<i class="sys-icons stay-deal-with-down-icon"></i>' +
                    '</div>' +
                    '<div class="visual-block">' +
                    '<i class="sys-icons stay-deal-with-process-icon"></i>下一节点：' +
                    '<span>待调度室领导处理</span>' +
                    '</div>' +
                    '</div>';
                break;
            case 2 :
                processPromptHtml = '<div class="has-complete-process">' +
                    '<i class="sys-icons has-complete-process-icon"></i>' +
                    '<span>流程已结束</span>' +
                    '</div>';
                break;
        }

        $target.after(processPromptHtml);
    }

    common.processPrompt = processPrompt;
    common.loadContentMain = loadContentMain;
    common.eachSeries = eachSeries;
    common.getScript = getScript;
    common.moveTableTitle = moveTableTitle;
    common.initDatetimepicker = initDatetimepicker;
    common.fadeInDown = fadeInDown;
    common.fadeOutUp = fadeOutUp;
    common.alertMsg = alertMsg;
    common.alertError = alertError;
    common.alertInfo = alertInfo;
    common.alertConfirm = alertConfirm;
    common.IETester = IETester;
    common.textOverflowTips = textOverflowTips;
    common.clearForm = clearForm;
    common.fillFormData = fillFormData;
    common.taskArrow = taskArrow;
    common.circleTask = circleTask;
    common.autoAddTags = autoAddTags;
    common.mailAutoComplete = mailAutoComplete;
    common.numToFloat = numToFloat;
    common.init = function () {
        eventHandler();
        testBrowser();
    };

    return parent;
}(ADMIN || {}, jQuery));
